var baseUrl = "/api/bd";

//事发地址
var sites = []
//被诉主体
var subjects = []

//智能预载
function identification() {
    // $('.antistop').val('12312313');
    //来电内容
    var parameter = $('.phoneRemark').val();
    //来电内容去除换行符/n
    parameter = parameter.replace(/[\r\n]/g, '');
    //影响范围
    let beginIndex = parameter.indexOf("涉及金额:");
    let endIndex = parameter.indexOf("涉及人数:")
    //涉及金额
    let involveMoney = parameter.substring(beginIndex, endIndex)
    //涉及人数
    let involvePreson = parameter.substring(endIndex, parameter.length)

    if (beginIndex != -1 && endIndex != -1) {
        if (involvePreson == '涉及人数:' && involveMoney == '涉及金额:') {
            $('#incidence').val("");
        } else if (involvePreson == '涉及人数:') {
            $('#incidence').val(involveMoney);
        } else if (involveMoney == '涉及金额:') {
            $('#incidence').val(involvePreson);
        } else {
            $('#incidence').val(involveMoney + "," + involvePreson);
        }

    } else {
        $('#incidence').val();
    }


    //联系电话
    var regx = /(1[3|4|5|7|8][\d]{9}|0[\d]{2,3}-[\d]{7,8}|400[-]?[\d]{3}[-]?[\d]{4})/g;
    var phoneNums = parameter.match(regx);
    if (phoneNums) {
        for (var i = 0; i < phoneNums.length; i++) {
            var temp = phoneNums[i]
            // $(".relationPhone").val(temp);
        }
    }

    if (parameter.length <= 0) {
        alert("请输入来电内容");
    } else {
        //关键字
        //Bootstrap tagsinput自定义标签插件
        //初始化删除所有标签
        $('.antistop').tagsinput('removeAll');
        var gjz = {'letter': parameter};


        //内容类别
        //初始化清除所有option
        $("#remarkCategory").empty();
        var nrlb = {"workOrders": [{"title": "", "content": parameter}]};
        $.ajax({
            url: baseUrl + "/workorder",
            data: JSON.stringify(nrlb),
            type: "POST",
            contentType: "application/json",
            dataType: "json",
            success: function (data) {
                var value = '';
                var text = '';
                if (data) {
                    //获取叶子节点
                    value = data[0][0]['level3_code'];
                    text = data[0][0]['level3'];
                    if (!value || value.length == 0) {
                        value = data[0][0]['level2_code'];
                        text = data[0][0]['level2'];
                    }
                    if (!value || value.length == 0) {
                        value = data[0][0]['level1_code'];
                        text = data[0][0]['level1'];
                    }
                }
                // $('#qxCT').combobox('setValue', value);
                $('#qxCT').combobox('setText', text);
                $("#txtDcntAcode").val(value);
                $("#txtDCntAName").val(text);
            }
        });

        // 被诉主体
        //初始化清空
        $('#subject').val("");
        $.ajax({
            url: baseUrl + "/argument",
            type: "POST",
            data: JSON.stringify({content: parameter}),
            contentType: "application/json",
            dataType: "json",
            success: function (data) {
                if (data[0].subject != null) {
                    $('#subject').val(data[0].subject.text);
                    subjects = data[0];
                    return
                } else if (data[0].place != null) {
                    $('#subject').val(data[0].place.text);
                    subjects = data[0];
                    return
                } else if (data[0].mention != null) {
                    $('#subject').val(data[0].mention.text);
                    subjects = data[0];
                    return
                } else {
                    subjects = [];
                }
            }
        });
    }
}


// //类案推荐
// $(".recommendli").click(function () {
//     let title = $('#qxCT').combo('getText');
//     if (title.length <= 0) {
//         $.modal.msgWarning("请输入内容类别");
//         $('#qxCT').blur()
//         return false
//     } else {
//         //修改a标签的href链接：
//         // $('#recommend').attr('href', '/test.html?content=' + $('.phoneRemark').val());
//         var url = '/caseRecommend.html?title=' + title;
//         document.getElementById('myIframe').src = url;
//     }
// });

// 点击同号工单
$('#phoneWork').click(function () {
    if ($('#fromTelA').val().length <= 0) {
        $.modal.msgWarning("请输入来电号码");
        $('#phoneWork').blur()
        return false
    } else {
        var url = '/jackPerLine.html?fromTelA=' + $('#fromTelA').val();
        document.getElementById('myIframe').src = url;
    }
});

//地址画像
$('#telHistoryByAddress').click(function () {
    if ($('#fmAddress').val().length <= 0) {
        $.modal.msgWarning("请输入事发地址");
        $('#fmAddress').blur()
        return false
    } else {
        var url = '/telHistoryByAddress.html?fmAddress=' + $('#fmAddress').val();
        document.getElementById('myIframe').src = url;
    }
});

//历史来电
//已修改为地址画像
$("#telHistory").click(function () {
    if ($('#fromTelA').val().length <= 0) {
        $.modal.msgWarning("请输入来电号码");
        $('#telHistory').blur()
        return false
    } else {
        var url = '/telHistory.html?fromTelA=' + $('#fromTelA').val();
        document.getElementById('myIframe').src = url;
    }
});

//关联推荐
$("#relevance").click(function () {
    var keyWord = $('.antistop').val();
    if (keyWord.length <= 0) {
        $.modal.msgWarning("请输入热词标签");
        $('#keyword').blur()
        return false
    } else {
        document.getElementById('myIframe').src = '/relevanceRec.html?keyWord=' + keyWord;
    }
})

//事发地址
//jq autocomplete插件
var sceneAddress = [];
var site = '';
// var sites = [];
$(".scene").autocomplete({
    source: function (request, response) {
        if (request.term.trim() !== '') {  //字符串不等于空字符串时进入
            //代码块
            $.ajax({
                url: baseUrl + "/search",
                dataType: "json",
                data: {address: request.term, city: '成都市'},
                complete: function (XMLHttpRequest, textStatus) {
                },
                success: function (data) {
                    // console.log(data)
                    sceneAddress = [];
                    var availableTags = [];
                    for (var i = 0; i < data.results.length; i++) {
                        availableTags.push(data.results[i].name + '<' + data.results[i].address + '>');
                        sceneAddress.push(data.results[i]);
                    }
                    response(availableTags);
                }
            });
        }
    },
    select: function (event, ui) {
        var str = ui.item.value;
        str = str.match(/<(\S*)>/)[1];
        console.log(str)
        for (var i = 0; i < sceneAddress.length; i++) {
            if (str == sceneAddress[i].address) {
                //存储选取到的事发地址
                site = sceneAddress[i]
                console.log(site)
                //    二维变一维
                sites = [];
                findChild(site, sites);
                console.log(sites)
            }
        }
    }
});

function findChild(data, list) {

    var item = data;
    var storeComment = ''
    if (item.storeComment.length > 0) {
        for (var i = 0; i < item.storeComment.length; i++) {
            storeComment += item.storeComment + '||'
        }
    }

    list.push({
        address: item.address,
        alias: item.alias,
        aoiName: item.aoiName,
        bid: item.bid,
        brandName: item.brandName,
        city: item.city,
        distance: item.distance,
        district: item.district,
        faceId: item.faceId,
        name: item.name,
        province: item.province,
        storePeriod: item.storePeriod,
        storeScore: item.storeScore,
        telephone: item.telephone,
        uid: item.uid,
        locationx: item.location.x,
        locationy: item.location.y,
        storeComment: storeComment
    });

};


//添加关键词标签
$('.antistop').on('beforeItemAdd', function (event) {
    // event.item: contains the item
    // event.cancel: set to true to prevent the item getting added
    //event.itme为添加的类容
    console.log("添加");
    console.log(event.item);
});
//删除关键词标签
$('.antistop').on('beforeItemRemove', function (event) {
    // event.item: contains the item
    // event.cancel: set to true to prevent the item getting removed
    //event.itme为删除的类容
    console.log("删除");
    console.log(event.item);
});
//标签
// function labelPage() {
//
//     var url = '/system/test/lablePage';
//     var title = '标签';
//     var height = '600px';
//     var width='400px'
//     var options = {
//         url: url,
//         title: title,
//         height: height,
//         width:width
//     }
//     popupDialog(options);
// }

// 添加工单标签
function labelPage() {
    var telId = $("[name='pkId']").val();
    var url = ctx + "system/tag/addTelWFTag?telId=" + telId;
    var title = "添加工单标签";
    $.modal.open(title, url, '800', '500', callback);
}

// 刷新当前页面
function callback(index, layero) {
    var iframeWin = layero.find('iframe')[0];
    iframeWin.contentWindow.submitHandler();
}

function popupDialog(options) {
    width = options.width || '85%';
    height = options.height || '85%';
    var index = layer.open({
        type: 2,
        area: [height, width],
        fix: false,
        maxmin: false,
        shade: 0.3,
        title: options.title,
        content: options.url,
        // btn: ['关闭'],
        // 弹层外区域关闭
        shadeClose: true,
        offset: 't',
        // yes: callback,
        cancel: function (index) {
            return true;
        }
    });
}


//    转值班长
function transfer() {
    var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
    parent.layer.close(index); //再执行关闭
    alert('转值班长，关闭');
}

//    当场解答
function answer() {
    var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
    // parent.layer.close(index); //再执行关闭
    // alert('当场解答，关闭');
    //关键词保存
    var data = [];
    $(".label-info").each(function () {
        data.push($(this).text());
    })
    //事发地址
    if (sites.length == 0) {
        $(".theAddress").val();
    } else {
        sites
    }
    sites
    //被诉主体
    subjects
    console.log(subjects)
    console.log(sites)
    console.log(data)

}

//    无效来电
function invalidPhone() {
    var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
    parent.layer.close(index); //再执行关闭
    alert('无效来电，关闭');
}

//    关闭
function gclose() {
    var name = $(this)[0].name;
    //判断是窗口关闭还是标签页关闭
    if (name.indexOf('layui-layer-iframe') != -1) {
        var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
        parent.layer.close(index); //再执行关闭
    } else {
        $.modal.closeTab();
    }

}

//类案推荐切换样式同号来电
$('#navUL li').click(function () {
    if ($('.phoneRemark').val().length <= 0) {

    } else {
        $('#navUL a').removeClass('current');
        $(this).children('a').addClass('current');
    }

    if ($('#fromTelA').val().length <= 0) {

    } else {
        $('#navUL a').removeClass('current');
        $(this).children('a').addClass('current');
    }

});

//
(function () {

    // //计算剩余字数
    // var textArea = $('.SeatsRemark');
    // var numItem = $('.SeatsRemarkI');
    // var max = numItem.text(); //i标签中的内容，也就是最多可以显示的字符数
    // var curLength = textArea.val().length; //当前的字符数
    //
    // textArea.attr('maxlength', max); //设置最大字符数，如果去掉的话，i标签内会出现负数
    // numItem.text(max - curLength); //实时更新i标签中的数量
    // textArea.on('input propertychange', function () {
    //     //$(this) ---> 指代textarea
    //     numItem.text(max - $(this).val().length);
    // });
    // //计算剩余字数
    // var phoneRemark = $('.phoneRemark');
    // var phoneRemarkI = $('.phoneRemarkI');
    // var phoneRemarkm = phoneRemarkI.text();
    // var phoneRemarkth = phoneRemark.val().length;
    //
    // phoneRemark.attr('maxlength', phoneRemarkm);
    // phoneRemarkI.text(phoneRemarkm - phoneRemarkth);
    // phoneRemark.on('input propertychange', function () {
    //     phoneRemarkI.text(phoneRemarkm - $(this).val().length);
    // });
    // //计算剩余字数
    // var opinion = $('.opinion');
    // var opinionI = $('.opinionI');
    // var opinionm = opinionI.text();
    // var opinionth = opinion.val().length;
    //
    // opinion.attr('maxlength', opinionm);
    // opinionI.text(opinionm - opinionth);
    // opinion.on('input propertychange', function () {
    //     opinionI.text(opinionm - $(this).val().length);
    // });
    //    绑定快捷键 ALT+Z
    shortcut = {
        'all_shortcuts': {},//All the shortcuts are stored in this array
        'add': function (shortcut_combination, callback, opt) {
            //Provide a set of default options
            var default_options = {
                'type': 'keydown',
                'propagate': false,
                'disable_in_input': false,
                'target': document,
                'keycode': false
            }
            if (!opt) opt = default_options;
            else {
                for (var dfo in default_options) {
                    if (typeof opt[dfo] == 'undefined') opt[dfo] = default_options[dfo];
                }
            }

            var ele = opt.target;
            if (typeof opt.target == 'string') ele = document.getElementById(opt.target);
            var ths = this;
            shortcut_combination = shortcut_combination.toLowerCase();

            //The function to be called at keypress
            var func = function (e) {
                e = e || window.event;

                if (opt['disable_in_input']) { //Don't enable shortcut keys in Input, Textarea fields
                    var element;
                    if (e.target) element = e.target;
                    else if (e.srcElement) element = e.srcElement;
                    if (element.nodeType == 3) element = element.parentNode;

                    if (element.tagName == 'INPUT' || element.tagName == 'TEXTAREA') return;
                }

                //Find Which key is pressed
                if (e.keyCode) code = e.keyCode;
                else if (e.which) code = e.which;
                var character = String.fromCharCode(code).toLowerCase();

                if (code == 188) character = ","; //If the user presses , when the type is onkeydown
                if (code == 190) character = "."; //If the user presses , when the type is onkeydown

                var keys = shortcut_combination.split("+");
                //Key Pressed - counts the number of valid keypresses - if it is same as the number of keys, the shortcut function is invoked
                var kp = 0;

                //Work around for stupid Shift key bug created by using lowercase - as a result the shift+num combination was broken
                var shift_nums = {
                    "`": "~",
                    "1": "!",
                    "2": "@",
                    "3": "#",
                    "4": "$",
                    "5": "%",
                    "6": "^",
                    "7": "&",
                    "8": "*",
                    "9": "(",
                    "0": ")",
                    "-": "_",
                    "=": "+",
                    ";": ":",
                    "'": "\"",
                    ",": "<",
                    ".": ">",
                    "/": "?",
                    "\\": "|"
                }
                //Special Keys - and their codes
                var special_keys = {
                    'esc': 27,
                    'escape': 27,
                    'tab': 9,
                    'space': 32,
                    'return': 13,
                    'enter': 13,
                    'backspace': 8,

                    'scrolllock': 145,
                    'scroll_lock': 145,
                    'scroll': 145,
                    'capslock': 20,
                    'caps_lock': 20,
                    'caps': 20,
                    'numlock': 144,
                    'num_lock': 144,
                    'num': 144,

                    'pause': 19,
                    'break': 19,

                    'insert': 45,
                    'home': 36,
                    'delete': 46,
                    'end': 35,

                    'pageup': 33,
                    'page_up': 33,
                    'pu': 33,

                    'pagedown': 34,
                    'page_down': 34,
                    'pd': 34,

                    'left': 37,
                    'up': 38,
                    'right': 39,
                    'down': 40,

                    'f1': 112,
                    'f2': 113,
                    'f3': 114,
                    'f4': 115,
                    'f5': 116,
                    'f6': 117,
                    'f7': 118,
                    'f8': 119,
                    'f9': 120,
                    'f10': 121,
                    'f11': 122,
                    'f12': 123
                }

                var modifiers = {
                    shift: {wanted: false, pressed: false},
                    ctrl: {wanted: false, pressed: false},
                    alt: {wanted: false, pressed: false},
                    meta: {wanted: false, pressed: false} //Meta is Mac specific
                };

                if (e.ctrlKey) modifiers.ctrl.pressed = true;
                if (e.shiftKey) modifiers.shift.pressed = true;
                if (e.altKey) modifiers.alt.pressed = true;
                if (e.metaKey) modifiers.meta.pressed = true;

                for (var i = 0; k = keys[i], i < keys.length; i++) {
                    //Modifiers
                    if (k == 'ctrl' || k == 'control') {
                        kp++;
                        modifiers.ctrl.wanted = true;

                    } else if (k == 'shift') {
                        kp++;
                        modifiers.shift.wanted = true;

                    } else if (k == 'alt') {
                        kp++;
                        modifiers.alt.wanted = true;
                    } else if (k == 'meta') {
                        kp++;
                        modifiers.meta.wanted = true;
                    } else if (k.length > 1) { //If it is a special key
                        if (special_keys[k] == code) kp++;

                    } else if (opt['keycode']) {
                        if (opt['keycode'] == code) kp++;

                    } else { //The special keys did not match
                        if (character == k) kp++;
                        else {
                            if (shift_nums[character] && e.shiftKey) { //Stupid Shift key bug created by using lowercase
                                character = shift_nums[character];
                                if (character == k) kp++;
                            }
                        }
                    }
                }

                if (kp == keys.length &&
                    modifiers.ctrl.pressed == modifiers.ctrl.wanted &&
                    modifiers.shift.pressed == modifiers.shift.wanted &&
                    modifiers.alt.pressed == modifiers.alt.wanted &&
                    modifiers.meta.pressed == modifiers.meta.wanted) {
                    callback(e);

                    if (!opt['propagate']) { //Stop the event
                        //e.cancelBubble is supported by IE - this will kill the bubbling process.
                        e.cancelBubble = true;
                        e.returnValue = false;

                        //e.stopPropagation works in Firefox.
                        if (e.stopPropagation) {
                            e.stopPropagation();
                            e.preventDefault();
                        }
                        return false;
                    }
                }
            }
            this.all_shortcuts[shortcut_combination] = {
                'callback': func,
                'target': ele,
                'event': opt['type']
            };
            //Attach the function with the event
            if (ele.addEventListener) ele.addEventListener(opt['type'], func, false);
            else if (ele.attachEvent) ele.attachEvent('on' + opt['type'], func);
            else ele['on' + opt['type']] = func;
        },

        //Remove the shortcut - just specify the shortcut and I will remove the binding
        'remove': function (shortcut_combination) {
            shortcut_combination = shortcut_combination.toLowerCase();
            var binding = this.all_shortcuts[shortcut_combination];
            delete (this.all_shortcuts[shortcut_combination])
            if (!binding) return;
            var type = binding['event'];
            var ele = binding['target'];
            var callback = binding['callback'];

            if (ele.detachEvent) ele.detachEvent('on' + type, callback);
            else if (ele.removeEventListener) ele.removeEventListener(type, callback, false);
            else ele['on' + type] = false;
        }
    }
    //快捷键ALT+Z
    shortcut.add("ALT+Z", function () {
        var sortModelName = $('.phoneRemark').val();
        var url = '/system/mTelRcd/cmnFile/findSortModel';
        var data = {sortModelName: sortModelName};
        $.ajax({
            url: url,
            data: data,
            type: "POST",
            dataType: "json",
            success: function (data) {
                $('.phoneRemark').val(data.data);
            }
        });
    });


})()